import 'dart:async';
import 'dart:convert';
import 'dart:ui' as ui;
import 'dart:ui';
import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cave_flutter/utils/extension/globalkey_extension.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:cave_flutter/model/user_model.dart';
import 'package:cave_flutter/style/whl_style.dart';

class QrCodeLogic extends GetxController {
  GlobalKey repaintWidgetKey = GlobalKey();
  late String urlString;
  ui.Image? avatarImage;
  UserModel? userModel;

  String QrUrl = '';

  @override
  void onInit() {
    super.onInit();
    getUserDetail();
    update();
  }

  getUserDetail() {
    WhlApi.getPersonDetail.get(
        {"accountId": WhlUserUtils.getUserInfo().accountId},
        withLoading: true).then((value) {
      if (value.isSuccess()) {
        userModel = UserModel.fromJson(value.data);
        QrUrl =
            'http://app.cave-meta.com:8888/register?inviteCode=${userModel?.userId}';
        update();
      }
    });
  }

  Future capturePngAndSaveImage() async {
    Uint8List? imageData = await repaintWidgetKey.screenShot();
    //保存图片到相册
    final result = await ImageGallerySaver.saveImage(imageData!);
    if (result['isSuccess']) {
      BotToast.showText(text: '保存成功');
    } else {
      BotToast.showText(text: '保存失败');
    }
  }

  doClickShareLinks() async {}

  Future<ui.Image> loadImageData(String imageUrl) async {
    // try {
    // Load the image as Uint8List using CachedNetworkImageProvider
    final provider = CachedNetworkImageProvider(imageUrl);
    final ImageStream stream = provider.resolve(ImageConfiguration.empty);
    final Completer<Uint8List> completer = Completer<Uint8List>();
    final Completer<ui.Image> imageCompleter = Completer<ui.Image>();

    stream.addListener(
        ImageStreamListener((ImageInfo info, bool synchronousCall) async {
      final ByteData? imageData =
          await info.image.toByteData(format: ImageByteFormat.png);
      if (completer.isCompleted) {
        return;
      }
      completer.complete(imageData?.buffer.asUint8List());
    }));

    await completer.future;

    // Save the image to gallery
    final Uint8List bytes = await completer.future;
    ui.decodeImageFromList(bytes, imageCompleter.complete);
    return await imageCompleter.future;
    // } catch (e) {
    //   print(e);
    // }
  }
}
